<template>
  <h1>部门管理</h1>
  <div class="container">
    <el-button type="primary" @click="addDeptBtn">+ 添加部门</el-button>
  </div>
  <div class="container">
    <el-table :data="deptList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column prop="name" label="部门名称" width="300" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" width="400" align="center">
        <template #default="{ row }">{{ parseTime(row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link key="primary" type="primary" size="small" @click="editDeptBtn(scope.row.id)">编辑</el-button>
          <el-button link key="danger" type="danger" size="small" @click="deleteDept(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="deptDialogVisible" :title="deptDialogTitle" width="500">
    <el-form ref="deptFormRef" :model="deptForm" :rules="deptRules" label-width="auto">
      <el-form-item label="部门名称" prop="name">
        <el-input placeholder="请输入部门名称，长度为2～10位" v-model="deptForm.name" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDept"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import {
  getAllDeptList,
  addDept,
  getDeptById,
  updateDept,
  deleteDeptApi
} from '@/api/dept.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { parseTime } from '@/utils/date.js';

const deptList = ref([]);
const deptDialogVisible = ref(false);
const deptDialogTitle = ref('');
const deptFormRef = ref(null);
const deptForm = ref({
  name: ''
});

const deptRules = ref({
  name: [
    {
      required: true,
      message: '请输入部门名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 10,
      message: '部门名称长度在2~10个字符',
      trigger: 'blur'
    }
  ]
});

onMounted(() => {
  getDeptList();
});

// 获取部门列表
const getDeptList = async () => {
  const res = await getAllDeptList();
  if (res.code === 1) {
    deptList.value = res.data;
  }
};

// 点击添加部门按钮
const addDeptBtn = () => {
  deptDialogTitle.value = '添加部门';
  deptDialogVisible.value = true;
  deptForm.value = {
    name: ''
  };
  // 清空校验
  if (deptFormRef.value) {
    deptFormRef.value.clearValidate();
  }
};

// 点击编辑部门按钮
const editDeptBtn = async (id) => {
  await getDeptById(id).then((res) => {
    if (res.code === 1) {
      deptForm.value = res.data;
    }
  });
  // 清空校验
  if (deptFormRef.value) {
    deptFormRef.value.clearValidate();
  }
  deptDialogTitle.value = '编辑部门';
  deptDialogVisible.value = true;
};

// 保存部门
const saveDept = () => {
  if (!deptFormRef.value) return;
  deptFormRef.value.validate(async (valid) => {
    if (valid) {
      let res;
      if (deptForm.value.id) {
        res = await updateDept(deptForm.value);
      } else {
        res = await addDept(deptForm.value);
      }
      if (res.code === 1) {
        if (deptForm.value.id) {
          ElMessage.success('修改成功');
        } else {
          ElMessage.success('添加成功');
        }
        deptDialogVisible.value = false;
        getDeptList();
      } else {
        ElMessage.error(res.msg);
      }
    }
  });
};

// 删除部门
const deleteDept = async (id) => {
  ElMessageBox.confirm('确定删除该部门吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(async () => {
      const res = await deleteDeptApi(id);
      if (res.code === 1) {
        ElMessage.success('删除成功');
        getDeptList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.info('您已取消删除');
    });
};
</script>

<style scoped>
.container {
  margin: 20px 0;
}
</style>
